//
//  AsyncGetModel.m
//  UI_豆瓣
//
//  Created by 付正 on 14-11-7.
//  Copyright (c) 2014年 付正. All rights reserved.
//

#import "AsyncGetModel.h"

@implementation AsyncGetModel
- (void)dealloc
{
    Block_release(_finishedBlock);
    [_data release];
    [super dealloc];
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        self.data = [NSMutableData data];
    }
    return self;
}


+ (void)asyncWithUrl:(NSString *)urlstr dic:(NSMutableDictionary *)dic block:(FinishdedBlock)block
{
    AsyncGetModel *model = [[AsyncGetModel alloc] init];
    model.finishedBlock = block;
    [model startWithUrl:urlstr parmaters:dic];
    [model release];
}






+ (NSString *)urlWithUrlStr:(NSString *)urlstr parmaters:(NSDictionary *)parmaters
{
    NSString *my = @"";
    for (NSString *key in [parmaters allKeys]) {
        if ([my length] == 0) {
            my = [NSString stringWithFormat:@"?%@=%@", key, [parmaters objectForKey:key]];
        } else {
            my = [NSString stringWithFormat:@"%@&%@=%@", my, key, [parmaters objectForKey:key]];
        }
    }
    
    urlstr = [NSString stringWithFormat:@"%@%@", urlstr, my];
    return urlstr;
}




- (void)startWithUrl:(NSString *)urlstr parmaters:(NSDictionary *)parmaters
{
    urlstr = [AsyncGetModel urlWithUrlStr:urlstr parmaters:parmaters];
    urlstr = [urlstr stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURL *url = [NSURL URLWithString:urlstr];
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
    [request setHTTPMethod:@"GET"];
    [NSURLConnection connectionWithRequest:request delegate:self];
}


- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{

    
    
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{

    [self.data appendData:data];
    
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    self.finishedBlock(_data);
}













@end
